package com.ljkj.cordial.chat.plugins.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.lanjiu.lib.utils.log.Logger;

/**
 * @description:
 * @author: Panwei
 * @date: 2020/3/19 11:11
 */
public class ScreenPlugReceiver extends BroadcastReceiver {

    private static boolean isScreenOpen = true;
    private OnScreenStateChangedListener mOnScreenStateChangedListener;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_SCREEN_OFF.equals(action)) {
            isScreenOpen = false;
            if (mOnScreenStateChangedListener != null)
                mOnScreenStateChangedListener.onScreenStateChanged(false);
        } else if (Intent.ACTION_SCREEN_ON.equals(action)) {
            isScreenOpen = false;
            if (mOnScreenStateChangedListener != null)
                mOnScreenStateChangedListener.onScreenStateChanged(false);
        } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
            isScreenOpen = true;
            if (mOnScreenStateChangedListener != null)
                mOnScreenStateChangedListener.onScreenStateChanged(true);
        }
    }

    public void setOnScreenStateChangedListener(OnScreenStateChangedListener mOnScreenStateChangedListener) {
        this.mOnScreenStateChangedListener = mOnScreenStateChangedListener;
    }

    public static boolean isIsScreenOpen() {
        return isScreenOpen;
    }

    public void register(Context context) {
        register(context, null);
    }

    public void register(Context context, OnScreenStateChangedListener mOnScreenStateChangedListener) {
        setOnScreenStateChangedListener(mOnScreenStateChangedListener);
        IntentFilter screenFilter = new IntentFilter();
        screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
        screenFilter.addAction(Intent.ACTION_SCREEN_ON);
        screenFilter.addAction(Intent.ACTION_USER_PRESENT);
        context.registerReceiver(this, screenFilter);
    }

    public void unregister(Context context) {
        context.unregisterReceiver(this);
    }

    public interface OnScreenStateChangedListener {
        void onScreenStateChanged(boolean isOpen);
    }
}
